package com.xbongbong.pro.dataset.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xbongbong.paas.bi.pojo.dto.DataSetParseDTO;
import com.xbongbong.paas.bi.pojo.vo.DataSetResultVO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.wrap.BaseVO;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.dataset.service.DataSetPreViewResultService;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Objects;

/**
 * 描述信息
 *
 * @ClassName DataSetTestController
 * @Author 梁鲁江
 * 创建时间 2022/5/30 19:45
 * 修改时间  2022/5/30 19:45
 **/
@RestController
@RequestMapping(value = XbbProConstant.API_ROOT_PREFIX + "/dsValue")
public class DataSetPreViewController {
    @Resource
    private DataSetPreViewResultService dataSetPreViewResultService;
    @RequestMapping(value = "/preview", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String ckResult(@RequestBody @Valid DataSetParseDTO dataSetParseDTO, BindingResult br) {
        XbbResponse<BaseVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                if(!dataSetParseDTO.isPreView()){
                    dataSetParseDTO.setPreView(true);
                }
                DataSetResultVO ckResultServiceResult = dataSetPreViewResultService.getResult(dataSetParseDTO, dataSetParseDTO.getReqSource());
                response = new XbbResponse<>(ckResultServiceResult);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }
}
